package com.hdu.h_health.ui;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.hdu.h_health.R;
import com.hdu.h_health.bean.User;
import com.hdu.h_health.common.BaseActivity;
import com.hdu.h_health.event.FinishEvent;
import com.hdu.h_health.model.UserModel;
import com.hdu.h_health.widget.MyEditText;
import com.hdu.h_health.widget.NavigationView;
import com.orhanobut.logger.Logger;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;


/**
 * 用户登录界面
 * Created by 612 on 2016/2/27.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    @Bind(R.id.navView)
    NavigationView navView;
    private MyEditText usernameEt, passwordEt;
    private Button login;
    private TextView register;
    private CheckBox checkBox;//记住密码选择框

    private SharedPreferences sharedPreferences;//在本地储存一些用户基本的信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //设置监听器
        login.setOnClickListener(this);
        register.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(this);
        boolean isCheck = sharedPreferences.getBoolean("isCheck", false);
        //checkBox被选中
        if (isCheck) {
            String currentPassword = sharedPreferences.getString("currentPassword", null);
            String currentUsername = sharedPreferences.getString("currentUsername", null);
            passwordEt.setText(currentPassword);
            usernameEt.setText(currentUsername);
            checkBox.setChecked(true);
        }
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        usernameEt = (MyEditText) findViewById(R.id.username);
        passwordEt = (MyEditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login_btn);
        register = (TextView) findViewById(R.id.register_btn);
        checkBox = (CheckBox) findViewById(R.id.checkBox);

        //获得sharePreference对象
        sharedPreferences = this.getSharedPreferences("UserInfo", LoginActivity.MODE_PRIVATE);

        navView.setTv_title("登录");
        navView.getIv_left().setImageResource(R.drawable.ic_keyboard_arrow_left_white_36dp);
        navView.setClickListener(new NavigationView.ClickCallBack() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
    }

    //设置各控件点击事件
    @Override
    public void onClick(View v) {
        //EditText失去焦点
        usernameEt.setFocusable(false);
        passwordEt.setFocusable(false);
        switch (v.getId()) {
            case R.id.login_btn:
                UserModel.getInstance().login(this, usernameEt.getText().toString(), passwordEt.getText().toString(), new LogInListener() {

                    @Override
                    public void done(Object o, BmobException e) {
                        if (e == null) {
                            User user = (User) o;
                            //更新当前用户资料
                            BmobIM.getInstance().updateUserInfo(new BmobIMUserInfo(user.getObjectId(), user.getUsername(), user.getAvatar()));


                             /*登录成功后连接聊天服务器*/
                            User currentUser = UserModel.getInstance().getCurrentUser();
                            BmobIM.connect(currentUser.getObjectId(), new ConnectListener() {
                                @Override
                                public void done(String uid, BmobException e) {
                                    if (e == null) {
                                        Logger.i("connect success");
                                    } else {
                                        Logger.e(e.getErrorCode() + "/" + e.getMessage());
                                    }
                                }
                            });

                            finish();
//                            startActivity(MainActivity.class, null, true);

                        } else {
                            toast(e.getMessage() + "(" + e.getErrorCode() + ")");
                        }
                    }
                });
                break;
            case R.id.register_btn:
                startActivity(RegisterActivity.class, null, false);
                break;
        }
        //重新获取焦点
        usernameEt.setFocusableInTouchMode(true);
        passwordEt.setFocusableInTouchMode(true);
    }

    //checkbox监听器
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //初始化SharedPreferences编辑器
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //选中即记住密码
        if (isChecked) {
            String currentUsername = usernameEt.getText().toString();
            String currentPassword = passwordEt.getText().toString();
            if (!currentUsername.isEmpty() && !currentPassword.isEmpty()) {
                editor.putString("currentUsername", currentUsername);
                editor.putString("currentPassword", currentPassword);
                editor.putBoolean("isCheck", true);
            } else {
                editor.clear();
            }
        } else {
            editor.clear();
        }
        editor.apply();
    }

    //接收RegisterActivity注册成功后发送的“结束事件”消息
    public void onEvent(FinishEvent event) {
        finish();
    }
}
